package com.example.memo2.ui

import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.example.memo2.data.database.MemoDatabase
import com.example.memo2.data.model.Memo
import com.example.memo2.data.repository.MemoRepository
import com.example.memo2.notification.ReminderManager
import kotlinx.coroutines.launch
import java.util.Date

class MemoViewModel(application: Application) : AndroidViewModel(application) {
    
    private val repository: MemoRepository
    private val reminderManager = ReminderManager(application)
    
    private val _selectedDate = MutableLiveData<Date>()
    val selectedDate: LiveData<Date> = _selectedDate
    
    val allMemos: LiveData<List<Memo>>
    
    init {
        val memoDao = MemoDatabase.getDatabase(application).memoDao()
        repository = MemoRepository(memoDao)
        allMemos = repository.getAllMemos()
        _selectedDate.value = Date()
    }
    
    fun getMemosByDate(date: Date): LiveData<List<Memo>> {
        return repository.getMemosByDate(date)
    }
    
    suspend fun insertMemo(memo: Memo): Long {
        return repository.insertMemo(memo)
    }
    
    fun updateMemo(memo: Memo) = viewModelScope.launch {
        repository.updateMemo(memo.copy(updatedAt = Date()))
    }
    
    fun deleteMemo(memo: Memo) = viewModelScope.launch {
        // 先取消提醒
        reminderManager.cancelReminder(memo.id)
        // 再删除备忘录
        repository.deleteMemo(memo)
    }
    
    fun deleteMemosByIds(ids: List<Long>) = viewModelScope.launch {
        // 先取消所有相关提醒
        ids.forEach { memoId ->
            reminderManager.cancelReminder(memoId)
        }
        // 再删除备忘录
        repository.deleteMemosByIds(ids)
    }
    
    fun searchMemos(query: String): LiveData<List<Memo>> {
        return repository.searchMemos(query)
    }
    
    fun setSelectedDate(date: Date) {
        _selectedDate.value = date
    }
    
    suspend fun getMemoById(id: Long): Memo? {
        return repository.getMemoById(id)
    }
} 